<!--
基本信息--使用elelmentuiplus
-->

<template>
  <div>
    <el-form :model="baseInfo" :rules="rules" ref="formRef">
      <!--   第一行   -->
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="合同类型" prop="Type">
            <el-select disabled
                v-model="baseInfo.Type"
                filterable
                clearable
                remote
                reserve-keyword
                placeholder="请选择合同类型"
                remote-show-suffix
            >
              <el-option label="正式合同" value="0"></el-option>
              <el-option label="虚拟合同" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合同名称" prop="ContractName" >
            <el-input v-model="baseInfo.ContractName" placeholder="请输入合同名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="baseInfo.Type =='0'">
          <el-form-item label="合同编号" prop="ContractNum" >
            <el-input v-model="baseInfo.ContractNum" placeholder="请输入合同编号" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合同类型" prop="ContractType">
            <el-select disabled
                v-model="baseInfo.ContractType"
                filterable
                clearable
                remote
                reserve-keyword
                placeholder="请选择合同类型"
                remote-show-suffix
            >
              <el-option label="销售合同" value="0"></el-option>
              <el-option label="采购合同" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="项目名称" prop="ProjectName">
            <el-input disabled v-model="baseInfo.ProjectName" placeholder="请输入项目名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="售前号" prop="SaleNum">
            <el-input disabled v-model="baseInfo.SaleNum" placeholder="请输入售前号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="工作号" prop="JobNum">
            <el-input disabled v-model="baseInfo.JobNum" placeholder="请输入工作号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="标的物是否合规" prop="IsCompliance">
            <el-select disabled
                v-model="baseInfo.IsCompliance"
                filterable
                clearable
                remote
                reserve-keyword
                placeholder="请选择标的物是否合规"
                remote-show-suffix
            >
              <el-option label="是" :value="true"></el-option>
              <el-option label="否" :value="false"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!--   第二行   -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="客户合同编号" prop="CustContractNum">
            <el-input disabled v-model="baseInfo.CustContractNum" placeholder="请输入客户合同编号"> </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="6">
        <el-form-item label="客户" prop="CustCode">
            <el-select disabled
                v-model="baseInfo.CustCode"
                filterable
                remote
                reserve-keyword
                placeholder="请选择客户"
                :remote-method="cnvbasdocMethod"
                :loading="state.loading"
                @change="changeCustCode"
                remote-show-suffix
            >
              <el-option
                  v-for="item in cusoptions"
                  :key="item.cCusCode"
                  :label="item.ccusabbname"
                  :value="item.cCusCode">
                <span style="float: left">{{ item.ccusabbname }}</span>
                <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px;">【{{item.cCusCode}}】</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

<!--        <el-col :span="8">-->
<!--          <el-form-item label="评审类型" prop="PSType">-->
<!--            <el-select-->
<!--                v-model="baseInfo.PSType"-->
<!--                filterable-->
<!--                clearable-->
<!--                remote-->
<!--                reserve-keyword-->
<!--                placeholder="请选择评审类型"-->
<!--                remote-show-suffix-->
<!--            >-->
<!--              <el-option label="正常合同评审" value="0"></el-option>-->
<!--              <el-option label="无合同评审" value="1"></el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
        <el-col :span="6">
          <el-form-item label="客户地址" prop="CustAdd">
            <el-input disabled v-model="baseInfo.CustAdd" placeholder="请输入客户地址"> </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="支付款项" prop="Payment">
            <el-select disabled
                v-model="baseInfo.Payment"
                filterable
                clearable
                multiple
                remote
                reserve-keyword
                placeholder="请选择支付款项"
                remote-show-suffix
            >
              <el-option label="电汇" value="0"></el-option>
              <el-option label="支票" value="1"></el-option>
              <el-option label="银行承兑" value="2"></el-option>
              <el-option label="保理（无追索权）" value="3"></el-option>
              <el-option label="供应链融资（无追索权）" value="4"></el-option>
              <el-option label="商业承兑（原则不允许）" value="5"></el-option>
            </el-select>
          </el-form-item>
        </el-col>


      </el-row>
      <!--   第三行   -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="开户行" prop="BankCode">
            <el-input disabled v-model="baseInfo.BankCode" placeholder="请输入开户行"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="银行账号" prop="BankAccount">
            <el-input disabled v-model="baseInfo.BankAccount" placeholder="请输入银行账号"> </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="税号" prop="Tax">
            <el-input disabled v-model="baseInfo.Tax" placeholder="请输入税号"> </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="税率" prop="Rate">
            <el-input disabled v-model="baseInfo.Rate" placeholder="请输入税率">
              <template #append>%</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="交付时间" prop="DeliveryDate">
            <el-date-picker disabled
                v-model="baseInfo.DeliveryDate"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                type="date"
                clearable
                placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="交付地点" prop="DeliveryLocation">
            <el-input disabled v-model="baseInfo.DeliveryLocation" placeholder="请输入交付地点"> </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="签订地点" prop="SigningLocation">
            <el-input disabled v-model="baseInfo.SigningLocation" placeholder="请输入签订地点"> </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="合同金额" prop="ContractAmount">
            <el-input disabled v-model="baseInfo.ContractAmount" placeholder="请输入合同金额"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="卸货方式" prop="Unload">
            <el-select disabled
                v-model="baseInfo.Unload"
                filterable
                clearable
                remote
                reserve-keyword
                placeholder="请选择卸货方式"
                remote-show-suffix
            >
              <el-option label="甲方卸货" value="0"></el-option>
              <el-option label="乙方卸货" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="包装要求" prop="PackRequirement">
            <el-select disabled
                v-model="baseInfo.PackRequirement"
                filterable
                clearable
                remote
                reserve-keyword
                placeholder="请选择包装要求"
                remote-show-suffix
            >
              <el-option label="普通包装" value="0"></el-option>
              <el-option label="木箱包装" value="1"></el-option>
              <el-option label="出口包装" value="2"></el-option>
              <el-option label="特殊包装" value="3"></el-option>
              <el-option label="其他" value="4"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="包装说明" prop="PackRequirementInfo">
            <el-input v-model="baseInfo.PackRequirementInfo" placeholder="请输入包装说明"> </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否合同模板" prop="IsMoudel">
            <el-select disabled
                v-model="baseInfo.IsMoudel"
                filterable
                clearable
                remote
                reserve-keyword
                placeholder="请选择是否合同模板合同"
                remote-show-suffix
            >
              <el-option label="是" :value="true"></el-option>
              <el-option label="否" :value="false"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="单据日期" prop="DDate2">
            <el-date-picker disabled
                v-model="baseInfo.DDate2"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                type="date"
                clearable
                placeholder="选择单据日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="签订日期" prop="Ddate">
            <el-date-picker disabled
                v-model="baseInfo.Ddate"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                type="date"
                clearable
                placeholder="选择签订日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="阶段性文件" prop="PhasedFile">
            <el-checkbox-group v-model="baseInfo.PhasedFile" disabled>
              <el-checkbox value="交货验收" name="type">
                交货验收
              </el-checkbox>
              <el-checkbox value="通电验收" name="type">
                通电验收
              </el-checkbox>

              <el-checkbox value="结算资料" name="type">
                结算资料
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="补充说明" prop="UnloadConvention">
            <el-input disabled v-model="baseInfo.UnloadConvention"  type="textarea" rows="4" placeholder="请输入补充说明"></el-input>
          </el-form-item>
        </el-col>



      </el-row>
    </el-form>
    <el-col :span="24">
      <t-table
          title="合同标的"
          :table="state.table"
          show-summary
          :columns="state.table.columns"
          :isShowPagination="false"
          ref="singleEdit"
          :listTypeInfo="state.listTypeInfo"
          @handleEvent="handleEvent"
          @validateError="validateError"
      >
        <!-- 自定义单元格编辑组件(多选下拉选择) -->
        <template #editHobby="{ scope }">
          <el-select disabled
                     v-model="scope.row[scope.column.property]"
                     filterable
                     remote
                     reserve-keyword
                     placeholder="请输入存货名称或编码"
                     remote-show-suffix
                     :remote-method="remoteMethod"
                     :loading="state.loading"
                     @change="(e) => updateInv(e, scope.row)"
                     style="width: 100%"
          >
            <el-option
                v-for="item in state.options"
                :key="item.cInvCode"
                :label="item.cInvCode"
                :value="item.cInvCode"
            >
              <span style="float: left">{{ item.cInvName }}</span>
              <span
                  style="
                  float: right;
                  color: var(--el-text-color-secondary);
                  font-size: 13px;
                "
              >
                {{ item.cInvCode }}
              </span>

            </el-option>
          </el-select>
        </template>
      </t-table>
    </el-col>
    <el-col :span="24">
      <t-table
          title="支付标准"
          :table="state.tableZfBz"
          :columns="state.tableZfBz.columns"
          :isShowPagination="false"
          show-summary
          ref="singleTowEdit"
          :listTypeInfo="state.listTypeInfo"
          @handleEvent="handleEvent"
          @validateError="validateError"
      >

        <template #TermID="{ scope }">
          <el-select
              v-model="scope.row[scope.column.property]"
              filterable
              remote
              reserve-keyword
              placeholder="请选择支付条件"
              remote-show-suffix
              @change="(e) => updateZfTk(e, scope.row)"
              style="width: 100%"
          >
            <el-option
                v-for="item in state.listTypeInfo"
                :key="item.Id"
                :label="item.Content"
                :value="item.Id"
            >
            </el-option>
          </el-select>
        </template>

        <template #uploadFile1="{ scope }">
          <upload :limit="1" v-model="scope.row[scope.column.property]" :disabled="true"></upload>
        </template>
        <template #uploadFile2="{ scope }">
          <upload :limit="1" v-model="scope.row[scope.column.property]" :disabled="true"></upload>
        </template>
        <template #uploadFile3="{ scope }">
          <upload :limit="1" v-model="scope.row[scope.column.property]" :disabled="true"></upload>
        </template>
      </t-table>
    </el-col>



  </div>
</template>

<script setup>
import {onMounted, ref, toRefs, watch} from "vue";
import {cubasdocStore} from "@/stores/modules/cubasdoc";
import {GetInventory2, GetTK} from "@/api/base";
import {checkForm, debounce} from "@/utils/util";
import upLoad from '@/components/Upload/index.vue'
import {createRouter as fileList} from "vue-router";
import {checkFildsStore} from "@/stores/modules/checkFilds";
const emit = defineEmits(['submit'])
defineOptions({ name: 'EntryBaseInfo' })
const props = defineProps({
  baseInfo: {
    type: String,
    default: ''
  },
  rules: {
    type: Object,
    default: () => {
      return {}
    }
  },
  subList: {
    type: Array,
    default: () => {
      return []
    }
  },
  tremZF: {
    type: Array,
    default: () => {
      return []
    }
  },
  Id:{
    type: String,
    default: ''
  },
})

let {
  baseInfo,
  rules,
  subList,
  tremZF,
  Id
} = toRefs(props)

//subList数据渲染
const singleEdit = ref(null)
const singleTowEdit = ref(null)
let formRef =ref({})


const checkFild = checkFildsStore()

// 编辑单元格监听事件
const handleEvent = (type, val, index) => {

}
// 清除校验规则
const validateTable = (resultArr) => {
  singleEdit.value.saveMethod(data => {

  })
  singleTowEdit.value.saveMethod(data => {

  })
  checkForm(formRef.value,checkFild)
}
// 重置表单
const reset = () => {
  singleEdit.value.resetFields()
}
const editDel = (item, index, row) => {
  //
  row.splice(index, 1)

}
// 错误校验提示
const validateError = list => {
  list.map(val => {
    checkFild.setData(val)
  })
}

//定义数据
const state = reactive({
  formData: {},
  loading:false,
  options:[],
  rules: {
    ContractNum: [
      {required: true, message: '请输入合同编号', trigger: 'blur'},
      {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
    ],
    EntryName: [
      {required: true, message: '请输入项目名称', trigger: 'blur'},
      {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
    ]
   },

  table: {
    border: true,
    rules: {
      CinvCode: [{ required: true, message: "请选择存货", trigger: "change" }],
      Unit: [{ required: true, message: "请输入单位", trigger: "blur" }],
      Price: [{ required: true, message: "请输入单价", trigger: "blur" }],
      Quantity: [{ required: true, message: "请输入数量", trigger: "blur" }],
      Amount: [{ required: true, message: "请输入总价", trigger: "blur" }]
    },
    // firstColumn: { type: "index", label: "行号",props:'LineNum' }, // 显示序列号
    data: [],
    columns: [
      {
        prop: "LineNum",
        label: "行号",
        minWidth: "60",
      },
      {
        prop: "CinvCode",
        label: "存货编码",
        placeholder: "请选择存货",
        minWidth: "160",
      },
        {
        prop: "CinvName",
        label: "存货名称",
          minWidth: "200",
        },
      {
        prop: "Unit",
        label: "单位",
        minWidth: "220",
        placeholder: "请输入单位",
      },
      {
        prop: "CustCinvName",
        label: "客户产品名称",
        minWidth: "120"
      },
      {
        prop: "CustCinvAdd",
        label: "客户产品规格",
        minWidth: "120"
      },
      {
        prop: "Price",
        label: "单价",
        minWidth: "180",
      },
      {
        prop: "Quantity",
        label: "数量",
        minWidth: "180",
      },
      {
        prop: "Amount",
        label: "价税合计",
        minWidth: "110",
      },
      {
        prop: "Rate",
        label: "税率",
        minWidth: "180",
      },
      {
        prop: "Tax",
        label: "税额",
        minWidth: "110",
      },
      {
        prop: "iNatPrice",
        label: "无税单价",
        minWidth: "110",
      },
      {
        prop: "iNatAmount",
        label: "无税金额",
        minWidth: "110",
      },
    ],
  },
  // 下拉选择项
  listTypeInfo: [],
  tableZfBz: {
    rules: {
      TermContent: [{ required: true, message: "请选择支付条款", trigger: "blur" }],
      TermID: [{ required: true, message: "请选择支付条款", trigger: "blur" }]
    },
    // firstColumn: { type: "index", label: "序列" }, // 显示序列号
    data: [],
    columns: [
      {
        prop: "LineNum",
        label: "行号",
        placeholder: "请选择支付标准",
        minWidth: "60",
      },
      {
        prop: "TermContent",
        label: "内容",
        minWidth: "220",
      },
      {
        prop: "Type",
        label: "支付类型",
        minWidth: "100",
      },
      {
        prop: "DataDay",
        label: "执行周期(天)",
        minWidth: "100",

      },
      {
        prop: "Ratio",
        label: "比例",
        minWidth: "160",

      },
      {
        prop: "Amount",
        label: "含税金额",
        minWidth: "120",
        placeholder: "请输入金额",
      },
    ],
  },

  //存货下拉
  invList :[]
})


// 数量change事件
const numChange = (val, prop, scope) => {

  state.table.data[scope.$index].Amount = val * state.table.data[scope.$index].Price
}

// 数量change事件
const numSubChange = (val, prop, scope) => {


  let contractAmount = props.baseInfo.ContractAmount;


  if (contractAmount!==null && contractAmount!==undefined && contractAmount!==''){
    if (prop=='Ratio'){
      state.tableZfBz.data[scope.$index].Amount = Number(contractAmount) * (Number(scope.row[prop])/100)

    }
    if (prop=='Amount'){
      state.tableZfBz.data[scope.$index].Ratio = (Number(scope.row[prop]) / Number(contractAmount))*100

    }
  }



}



const cubasdoc = cubasdocStore()


//实时更新同步数据
watch(() => props.subList, (newValue, oldValue) => {

      state.table.data = newValue
    }, { deep: true },

)//实时更新同步数据
watch(() => props.tremZF, (newValue, oldValue) => {

      state.tableZfBz.data = newValue
    }, { deep: true },
)


onMounted(() => {
  state.table.data = subList.value
  state.tableZfBz.data = tremZF.value

  getTermContent()
})


//获取条款内容
const getTermContent = debounce(async (data) => {

  let {Data} =  await GetTK({Code: props.Id,Name:''});
  state.listTypeInfo = Data

},false,300)



//选择项
const cusoptions = ref([])
const cnvbasdocMethod = (query) => {
  if (query) {
    state.loading = true
    setTimeout(() => {
      state.loading = false

      cusoptions.value = cubasdoc.data.filter((its) => {
        return (its.cCusCode.toLowerCase().includes(query.toLowerCase()) || its.ccusabbname.toLowerCase().includes(query.toLowerCase()))
      })
    }, 200)
  } else {
    cusoptions.value = []
  }
}

function  addTowTable () {
  state.tableZfBz.data.push({
    //获取最大行号加1
    LineNum: state.tableZfBz.data.length + 1,
    TermID: null,
    TermContent: null,
    File1: null,
    File2: null,
    File3: null,
  })
}

function  addOneTable () {
  state.table.data.push({
    //获取最大行号加1
    LineNum: state.table.data.length + 1,
    Amount: null,
    Quantity: null,
    Price: [],
    Unit: null,
    CinvName: null,
    CinvCode: null,
  })
}

//客户选择
function changeCustCode(e){

  //过滤客户
  let cusoptions = cubasdoc.data.filter((its) => {
    return (its.cCusCode.toLowerCase().includes(e.toLowerCase()))
  })[0]
  if (cusoptions){
    //赋值
    baseInfo.value.CustName = cusoptions.ccusabbname
    baseInfo.value.CustAdd = cusoptions.ccusAddress
    baseInfo.value.Tax = cusoptions.cCusRegCode
    baseInfo.value.BankCode = cusoptions.ccusbank
    baseInfo.value.BankAccount = cusoptions.ccusaccount
  }

}

//存货选择
function updateInv(e,row){

  //过滤客户
  let invoptions = state.invList.filter((its) => {
    return (its.cInvCode.toLowerCase().includes(e.toLowerCase()))
  })[0]
  if (invoptions){
    //赋值
    row.CinvName = invoptions.cInvName
    row.Unit = invoptions.cComUnitCode
  }

}
//支付条件选择
function updateZfTk(e,row){
  let zftk = state.listTypeInfo.filter((its) => {
    return (its.Id.toLowerCase().includes(e.toLowerCase()))
  })[0]
  if (zftk){
    //赋值
    row.TermContent = zftk.Content
  }
}


//查询存货 -- 增加防抖函数
const remoteMethod = debounce(async (query) => {
  if (query) {
    state.loading = true
    state.loading = false

    let invData = {
      Code: query,
    }
    let {Data} = await GetInventory2(invData)
    state.invList = Data
    state.options = state.invList.filter((item) => {
      return (item.cInvName.toLowerCase().includes(query.toLowerCase()) || item.cInvCode.toLowerCase().includes(query.toLowerCase()))
    })
  } else {
    state.options = []
  }
},200,false)



const validateForm = () => {

  // formRef.value.validate()
};

defineExpose({validateTable,formRef})

</script>

<style scoped lang="scss">

</style>
